﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ShureValidation.Fluent
{
    public class FluentProvider : IRulesProvider
    {
        /// <summary>
        /// Determines if the provider contains rules for a specific model.
        /// </summary>
        /// <param name="type">Type of model to fetch validations for</param>
        /// <returns><c>true</c> if this provider can validate the model; otherwise <c>false</c>.</returns>
        public bool Contains(Type type)
        {
            string name = type.AssemblyQualifiedName;
            int pos = name.IndexOf(",");
            name = name.Substring(0, pos) + "Validator" + name.Substring(pos);
            return Type.GetType(name) != null;
        }

        /// <summary>
        /// Create a new validator for the specified type
        /// </summary>
        /// <param name="type">Type to create validator for.</param>
        /// <returns>Validator if attributes was present; otherwise <c>null</c>.</returns>
        /// <exception cref="FormatException">A rule do not support the property type that is set to validate.</exception>
        public ModelValidator Create(Type type)
        {
            string name = type.AssemblyQualifiedName;
            int pos = name.IndexOf(",");
            name = name.Substring(0, pos) + "Validator" + name.Substring(pos);

            Type validatorType = Type.GetType(name);
            if (validatorType == null)
                return null;

            object instance = Activator.CreateInstance(validatorType);
            if (instance == null)
                return null;

            FluentValidator validator = (FluentValidator)instance;
            return validator.GetValidator();
        }
    }
}
